/**
 * @(#)MappedFile.java, 2011-3-5. 
 * 
 * Copyright 2011 Youdao, Inc. All rights reserved.
 * YOUDAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package pku.edb.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 *
 * @author guosq
 *
 */
public class MappedFile {
    private static final int length = 0x8FFFFFF/ 1024;  //128K
    public static void main(String[] args) throws IOException {
        MappedFile mappedFile = new MappedFile();
        mappedFile.write("test.tmp");
        mappedFile.read("test.tmp");
 
    }
    
    public void write(String filename) throws IOException {
        FileChannel fc = new RandomAccessFile(filename, "rw").getChannel();
        MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, length);
        int size = 10;
        for (int i = 0; i < size; ++i) {
            buf.putInt(i);
        }
        fc.close();
    }
    
    public void read(String filename) throws IOException {
        FileChannel fc = new RandomAccessFile(filename, "rw").getChannel();
        MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
        int size = 10;
        for (int i = 0; i < size; ++i) {
            System.out.println(buf.getInt());
        }
        System.out.println("Position:" + buf.position());
        buf.position(length);
        System.out.println("Position:" + buf.position());
        System.out.println(buf.getInt());
        System.out.println("Position:" + buf.position());
        fc.close();
    }
}
